package com.fancy.service;

/**
 *
 * @author Jackie
 * @date 2017/10/20
 */

import com.fancy.dao.PersonChatMessageDao;
import com.fancy.dao.StudentDao;
import com.fancy.dao.TeacherDao;
import entity.PersonChatMessage;
import entity.Student;
import entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class PersonChatService {

    private PersonChatMessageDao personChatMessageDao;

    private StudentDao studentDao;

    private TeacherDao teacherDao;

    @Autowired
    public PersonChatService(PersonChatMessageDao personChatMessageDao, StudentDao studentDao, TeacherDao teacherDao) {
        this.personChatMessageDao = personChatMessageDao;
        this.studentDao = studentDao;
        this.teacherDao = teacherDao;
    }

    public boolean addMessage(PersonChatMessage personChatMessage){
        boolean userValid = checkUser(personChatMessage);
        boolean result = false;
        if (userValid){
            result = personChatMessageDao.insertMessage(personChatMessage);
        }
        return result;
    }

    public List<PersonChatMessage> getConversation(String myID, String otherID){
        List<PersonChatMessage> total = new ArrayList<PersonChatMessage>();
        total.addAll(personChatMessageDao.findConversation(myID, otherID));
        total.addAll(personChatMessageDao.findConversation(otherID, myID));
        Collections.sort(total);
        return total;
    }

    public List<PersonChatMessage> getNotReadMessage(String myID, String otherID){
        List<PersonChatMessage> notReadMessage = personChatMessageDao.findNotReadMessage(myID, otherID);
        Collections.sort(notReadMessage);
        int size = notReadMessage.size();
        for (int i = 0 ; i < size ; i ++) {
            personChatMessageDao.updataMessageToRead(notReadMessage.get(i).id);
        }
        return notReadMessage;
    }

    private boolean checkUser(PersonChatMessage personChatMessage){
        String personFromID = personChatMessage.person_from_id;
        String personToID = personChatMessage.person_to_id;

        Student studentFrom = studentDao.findStudent(personFromID);
        Student studentTo = studentDao.findStudent(personToID);
        Teacher teacherFrom = teacherDao.findTeacher(personFromID);
        Teacher teacherTo = teacherDao.findTeacher(personToID);

        return (studentFrom != null||teacherFrom != null)&&(studentTo != null||teacherTo != null);
    }



}
